import { List } from 'immutable';
import ACTION_TYPE from '../../constant/action-types';
import { createReducer } from '../utils';

const initialState = List();

const reducer = {
  [ACTION_TYPE.ADD_API_PROVIDER](state, action) {
    const { payload } = action;
    return state.push(payload);
  },
  [ACTION_TYPE.REMOVE_API_PROVIDER](state, action) {
    const { payload } = action;
    const index = state.indexOf(payload);
    if (index > -1) {
      return state.remove(index);
    }
    return state;
  },
  [ACTION_TYPE.UPDATE_API_PROVIDER](state, action) {
    const { id, api } = action.payload;
    const index = state.findIndex(item => item.id === id);
    if (index > -1) {
      return state.update(index, () => api);
    }
    return state;
  },
  [ACTION_TYPE.SET_API_PROVIDER_LIST](state, action) {
    const { list } = action.payload;
    return list;
  }
};

export default createReducer(reducer, initialState);
